<?php
if (!defined('ABSPATH')) { exit; }

function scf_news_feed_shortcode($atts = []) {
    include_once(ABSPATH . WPINC . '/feed.php');
    $feeds_raw = get_option('scf_news_feeds', "https://36kr.com/feed\nhttps://feed.cnblogs.com/blog/sitehome/rss");
    $feeds = array_filter(array_map('trim', explode("\n", $feeds_raw)));

    $items = [];
    foreach ($feeds as $feed_url) {
        $feed = fetch_feed($feed_url);
        if (is_wp_error($feed)) {
            continue;
        }
        $maxitems = $feed->get_item_quantity(5);
        $feed_items = $feed->get_items(0, $maxitems);
        foreach ($feed_items as $item) {
            $title = $item->get_title();
            $link = $item->get_link();
            $date = $item->get_date('Y-m-d H:i');
            $desc = $item->get_description();
            $enclosure = $item->get_enclosure();
            $img = $enclosure ? $enclosure->get_link() : '';
            $items[] = [
                'title' => $title,
                'link' => $link,
                'date' => $date,
                'desc' => $desc,
                'img' => $img,
                'source' => $feed->get_title(),
            ];
        }
    }

    // 简单按日期排序
    usort($items, function($a, $b){
        return strcmp($b['date'], $a['date']);
    });

    ob_start();
    ?>
    <div class="scf-card scf-news">
        <div class="scf-card__header">
            <strong>图文资讯</strong>
        </div>
        <div class="scf-card__body scf-grid">
            <?php foreach ($items as $it): ?>
                <article class="scf-news__item">
                    <?php if (!empty($it['img'])): ?>
                        <div class="scf-news__thumb"><img src="<?php echo esc_url($it['img']); ?>" alt="thumb"></div>
                    <?php endif; ?>
                    <h4 class="scf-news__title">
                        <a href="<?php echo esc_url($it['link']); ?>" target="_blank" rel="noopener"><?php echo esc_html($it['title']); ?></a>
                    </h4>
                    <div class="scf-news__meta">
                        <span><?php echo esc_html($it['source']); ?></span>
                        <span> · <?php echo esc_html($it['date']); ?></span>
                    </div>
                    <p class="scf-news__desc"><?php echo wp_kses_post(wp_trim_words(wp_strip_all_tags($it['desc']), 40)); ?></p>
                </article>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
    return ob_get_clean();
}